package com.pkt.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.item.piketao.dao.Brand;
import com.piketao.common.pojo.PageInfo;
import com.pkt.item.mapper.BrandMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author admin
 */
@Service
public class BrandService {

    private final BrandMapper brandMapper;

    @Autowired
    public BrandService(BrandMapper brandMapper) {
        this.brandMapper = brandMapper;
    }

    public PageInfo queryBrandByPageAndSort(
            Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        // 开始分页
        PageHelper.startPage(page, rows);
        // 过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }
        if (StringUtils.isNotBlank(sortBy)&&desc!=null) {
            // 排序
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        // 查询
        Page<Brand> pageResult = (Page<Brand>) brandMapper.selectByExample(example);
        // 返回结果
        return new PageInfo<>(pageResult.getTotal(),pageResult.getPageNum(), pageResult.getResult());
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveBrand(Brand brand, List<Long> cids) {
        // 新增品牌信息
        int i = this.brandMapper.insertSelective(brand);
        if (i!=1){
            throw new RuntimeException();
        }
        // 新增品牌和分类中间表
        for (Long cid : cids) {
            this.brandMapper.insertCategoryBrand(cid, brand.getId());
        }
    }

    public List<Brand> queryBrandsByCid(Long cid) {

        return brandMapper.selectBrandsByCid(cid);
    }

    public Brand queryBrandById(Long id) {

        return brandMapper.selectByPrimaryKey(id);
    }
}